const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const dbPath = path.resolve(__dirname, '../database.db');
const db = new sqlite3.Database(dbPath, (err) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log('Connected to the database.');
  }
});

// 创建用户表
db.run(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL
  )
`);

// 创建待办事项表
db.run(`
  CREATE TABLE IF NOT EXISTS todos (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    title TEXT NOT NULL,
    completed BOOLEAN DEFAULT FALSE,
    FOREIGN KEY (user_id) REFERENCES users (id)
  )
`);

// 初始化用户数据
const initializeUsers = () => {
  const users = [
    { username: 'admin', password: 'password123' },
    { username: 'ddd', password: 'password123' }
  ];

  users.forEach(async (user) => {
    const existingUser = await User.findByUsername(user.username);
    if (!existingUser) {
      const hashedPassword = bcrypt.hashSync(user.password, 10);
      await User.create(user.username, hashedPassword);
    }
  });
};

initializeUsers();

module.exports = db;


